<template>
  <cloud-dialog
    v-model:visible="visible"
    :width="480"
    title="修改密码"
    :loading="loading"
    :mask-closable="false"
    :before-ok="handleOk"
    :before-close="handleClose"
    :before-open="handleOpen">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-form-item
        field="old_password"
        label="原密码"
        validate-trigger="blur"
        hide-asterisk
        asterisk-position="end">
        <a-input-password
          v-model.trim="formData.old_password"
          placeholder="请输入原密码"
          :input-attrs="{ autocomplete: 'off' }"
          class="cloud-pwd-icon"
          @input="
            (value: string) =>
              (formData.old_password = value.replace(/\s/g, ''))
          " />
      </a-form-item>
      <a-form-item
        field="new_password"
        label="新密码"
        validate-trigger="blur"
        hide-asterisk
        asterisk-position="end"
        class="new_password-form-item">
        <template #label>
          <section class="flex flex-col">
            <span class="text-sm/22px">新密码</span>
            <span class="text-xs text-4">
              请输入8-20个字符，需要包含大小写英文字母、数字和标点符号（除空格）</span
            >
          </section>
        </template>
        <a-input-password
          v-model.trim="formData.new_password"
          placeholder="请输入新密码"
          class="cloud-pwd-icon"
          @input="
            (value: string) =>
              (formData.new_password = value.replace(/\s/g, ''))
          "
          @blur="handleNewPwdBlur" />
      </a-form-item>
      <a-form-item
        field="confirm_password"
        label="确认新密码"
        validate-trigger="blur"
        hide-asterisk
        asterisk-position="end"
        class="mb-0!">
        <a-input-password
          v-model.trim="formData.confirm_password"
          placeholder="请再次输入新密码"
          class="cloud-pwd-icon"
          :input-attrs="{ autocomplete: 'off' }"
          @input="
            (value: string) =>
              (formData.confirm_password = value.replace(/\s/g, ''))
          " />
      </a-form-item>
    </a-form>
  </cloud-dialog>
</template>

<script setup lang="ts">
import { updateApiUserPasswordApi } from '@/apis/modules/auth'
import { useAppStore } from '@/stores/app'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'

const visible = defineModel<boolean>({ required: true })
const loading = ref(false)

const appStore = useAppStore()
const formRef = ref<FormInstance>()

const formData = reactive<any>({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    old_password: [
      {
        required: true,
        validator: validatePassword
      }
    ],
    new_password: [
      {
        required: true,
        message: '密码不能为空'
      },
      {
        validator(value, callback: (error?: string) => void) {
          if (value === formData.old_password) {
            return callback('新密码不能与原密码相同')
          }
        }
      },
      {
        validator: validatePassword
      }
    ],
    confirm_password: [
      {
        required: true,
        validator(value, callback) {
          if (!value) {
            return callback('请再次输入新密码')
          }

          if (value !== formData.new_password) {
            return callback('两次密码输入不一致')
          }
          return callback()
        }
      }
    ]
  }
  return res
})

const handleNewPwdBlur = () => {
  if (formData.confirm_password) {
    formRef.value?.validateField('confirm_password')
  }
}

const handleOk = async () => {
  const error = await formRef.value?.validate()
  if (error) return false
  // loading.value = true
  await updateApiUserPasswordApi(formData)
    .then(() => {
      formRef.value?.resetFields()
      ToastUtils.success('操作成功')
      visible.value = false
      appStore.clearLoginInfoAction()
    })
    .finally(() => {
      loading.value = false
    })
}
const handleClose = async () => {
  await formRef.value?.resetFields()
}
const handleOpen = async () => {
  formRef.value?.resetFields()
}
</script>

<style scoped lang="less">
// .new_password-form-item {
//   :deep(.arco-form-item-label-col) {
//     @apply flex flex-col mb-2;
//     &::after {
//       content: '请输入8-20个字符，需包含大小写英文字母、数字和标点符号（除空格）';
//       overflow: hidden;
//       color: var(----2color-text-5, #a6adb8);
//       text-overflow: ellipsis;
//       white-space: nowrap;
//       font-size: 12px;
//       font-style: normal;
//       font-weight: 400;
//       line-height: 20px;
//     }
//   }
// }
</style>
